package com.example.layui_project.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    public static final String ALGORITHM = "MD5";
    public static MessageDigest mDigest;

    static {
        mDigest = null;
        try {
            mDigest = MessageDigest.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("创建MD5加密对象出错");
        }
    }

    public static String md5to32string(String key) {
        try {
            mDigest.update(key.getBytes());
            return bytesToHexString(mDigest.digest());
        } catch (Exception e) {
            return String.valueOf(key.hashCode());
        }
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 255);
            if (hex.length() == 1) {
                builder.append('0');
            }
            builder.append(hex);
        }
        return builder.toString();
    }
}